import sys
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile, QWebEnginePage
from PyQt5.QtCore import QUrl, QRect
from PyQt5.QtGui import QIcon


class YandexOAuth(QMainWindow):
    def __init__(self, app_, *args, **kwargs):
        super(YandexOAuth, self).__init__(*args, **kwargs)

        self.app = app_
        self.token = None

        self.setWindowTitle("Yandex OAuth")
        self.setFixedSize(450, 700)
        self.setWindowIcon(QIcon("icon.png"))

        # Initialize the web browser widget and set its size
        self.init_browser()

    def init_browser(self):
        # Create a web browser widget and set its geometry
        self.browser = QWebEngineView(self)
        self.browser.setGeometry(QRect(0, 0, 500, 700))

        # Create a web engine profile and clear all cookies
        self.profile = QWebEngineProfile.defaultProfile()
        self.profile.cookieStore().deleteAllCookies()

        # Initialize a list to store cookies, and connect a callback function to capture new cookies
        self.cookies = []
        self.profile.cookieStore().cookieAdded.connect(lambda cookie: self.cookies.append(cookie))

        # Create a web engine page and set it as the page for the browser widget
        self.page = QWebEnginePage(self.profile)
        self.browser.setPage(self.page)

        # Load the Yandex OAuth URL
        url = "https://oauth.yandex.ru/authorize?response_type=token&client_id=23cabbbdc6cd418abb4b39c32c41195d"
        self.browser.load(QUrl(url))

        # Connect the "urlChanged" signal to the "on_url_changed" method
        self.browser.urlChanged.connect(self.on_url_changed)

        # Set the browser widget as the central widget and show the main window
        self.setCentralWidget(self.browser)
        self.show()

    def on_url_changed(self, url):
        # Callback function for the "urlChanged" signal
        url = url.url()
        if "#access_token" not in url:
            return
        # Extract the access token from the URL
        token = url.split("#access_token=")[1].split("&")[0]
        self.token = token
        # Close the main window after retrieving the token
        self.close()

    def closeEvent(self, event):
        # When the main window is closed, check if the token is present and emit it through the app
        if self.token:
            self.app.got_token.emit(self.token)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = YandexOAuth(app)
    sys.exit(app.exec_())
